#include "Block.h"

#include "Graphics.h"

#define BLOCK_SIZE 20

Block::Block(TetrisMap& map): map(map)
{
}

void Block::tryMove(int dx)
{
	this->dx = dx;
}

void Block::rotate()
{
	for (auto u : shape.units)
	{
		if (map.exist(x - u.y, y + u.x))
		{
			return;
		}
	}

	for (auto& u : shape.units)
	{
		int t = u.x;
		u.x = -u.y;
		u.y = t;
	}
}

bool Block::move()
{
	for (auto u : shape.units)
	{
		if (map.exist(x + u.x + dx, y + u.y))
		{
			return false;
		}
	}
	x += dx;
	dx = 0;
	return true;
}

bool Block::tryDrop()
{
	for (auto u : shape.units)
	{
		if (!map.floating(x + u.x, y + u.y))
		{
			return false;
		}
	}
	y++;
	return true;
}

void Block::setPosition(int x, int y)
{
	this->x = x;
	this->y = y;
}

void Block::setShape(Shape& inshape)
{
	shape.units.clear();
	for (Vec2 p : inshape.units)
	{
		shape.units.emplace_back(p);
	}
}

Block::Shape Block::newShape(int fixture[4][4], int cx, int cy)
{
	Shape s;
	for (int i = 0; i < 4; i++)
	{
		for (int j = 0; j < 4; j++)
		{
			if (fixture[i][j]) s.units.emplace_back(j - cx, i - cy);
		}
	}
	return s;
}

void Block::drawBlock(Graphics* graphics, Block& block, int mapx, int mapy, int color)
{
	for (auto u : block.shape.units)
	{
		graphics->drawRect(mapx + (block.x + u.x) * BLOCK_SIZE, mapy + (u.y + block.y) * BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE, color);
	}
}
